//class made by Teo ( www.teodorfilimon.com ). More about the app in readme.txt

package com.teo.tools.counter;

/**
 * This class represents the functional part of the clicker-counter.
 */
public final class Counter {

	/**
	 * This class comprises the state of the counter. It isn't used for internal
	 * storage, only for external interfacing.
	 */
	public class CounterState {
		public long count;
		public long millis;
		public long totalMillis;

		public CounterState(long c, long m, long t) {
			count = c;
			millis = m;
			totalMillis = t;
			Counter.currentState = this;
		}
	}

	public static CounterState currentState;
	//private long mChanges = 0;
	private long mCount;
	private long mCurrentTimeMillis = 0;
	private long mTotalElapsedMillis = 0;

	/**
	 * The only way to initialize the count is through the constructor
	 * 
	 * @param count
	 */
	public Counter(long count) {
		registerEvent();
		mCount = count;
	}

	/**
	 * @return The current value of the count
	 */
	public long getValue() {
		return mCount;
	}

	/**
	 * @return The number of counter events
	 *
	public long getChanges() {
		return mChanges;
	}*/

	/**
	 * Increments the count with 1
	 * 
	 * @return the new state (which is not checked)
	 */
	public CounterState increment() {
		return new CounterState(step(true), registerEvent(),
				mTotalElapsedMillis);
	}

	/**
	 * Decrements the count with 1
	 * 
	 * @return the new state (which is not checked)
	 */
	public CounterState decrement() {
		return new CounterState(step(false), registerEvent(),
				mTotalElapsedMillis);
	}

	/**
	 * Actually performs the incrementation or decrementation
	 * 
	 * @param up
	 *            - if true, it counts up, if not, it counts down
	 * @return the new value
	 */
	private long step(boolean up) {
		if (up) {
			mCount++;
		} else {
			mCount--;
		}
		/*if (TimeCounter.FREE) {
			if (mCount > 10) {
				mCount = 10;
			} else if (mCount < -10) {
				mCount = -10;
			}
		}*/
		return mCount;
	}

	/**
	 * Called when an incrementation or decrementation event occurs
	 * 
	 * @return millis elapsed since last event
	 */
	private long registerEvent() {
		//mChanges++;
		long currentMillis = System.currentTimeMillis();
		long millisElapsed = currentMillis - mCurrentTimeMillis;
		if (mCurrentTimeMillis > 0) {
			mTotalElapsedMillis += millisElapsed;
		}
		mCurrentTimeMillis = currentMillis;
		return millisElapsed;
	}

	/**
	 * Resets the counter to 0
	 * 
	 * @return the new reset state
	 */
	public CounterState resetCount() {
		return new CounterState(mCount = 0, registerEvent(),
				mTotalElapsedMillis);
	}

	public CounterState resetStats() {
		mCurrentTimeMillis = 0;
		mTotalElapsedMillis = 0;
		//mChanges=1;
		return new CounterState(mCount, registerEvent(), 0);
	}
}
